#include "stdafx.h"
#include "adaptorsocket.h"
#include "adaptorserver.h"

AdaptorSocket::AdaptorSocket(OrderLink *ol, AdaptorServer *server) {
	memset(mBuffer, 0, mBufSize);
	mBufLen = 0;
	mOrderLink = ol;
	mServer = server;
}


AdaptorSocket::~AdaptorSocket(void)
{
}


void AdaptorSocket::mProcBuffer() {
	int len = mBufLen, offset;
	char *src = mBuffer;

	while (len > 0) {
		offset = mProcOneMessage(src, len);
		if( offset > 0 ) {
			src += offset;
			len -= offset;
		} else {
			break;
		}
	}

	if(len == 0) {
		mBufLen = 0;
	} if ( len > 0 && src != mBuffer) {
		// move the remaining part
		memmove_s(mBuffer, mBufSize, src, len);
		mBufLen = len;
	}
}

int AdaptorSocket::mProcOneMessage(char *src, int len) {
	char type = *src;
	if ( ZAdaptorOrderMessage::Type == type && len >= ZAdaptorOrderMessage::Length ) {
		AdaptorOrder *msg = mOrderLink->getOrder();
		if( ZAdaptorOrderMessage::get(src, len, &msg->mOrder) ) {
			msg->mSocket = this;
			mOrderLink->managerOrder(msg);
			return ZAdaptorOrderMessage::Length;
		} else {
			mOrderLink->recycleOrder(msg);
		}
	} else if ( ZAdaptorLoginMessage::Type == type && len >= ZAdaptorLoginMessage::Length) {
		ZAdaptorLoginMessage msg;
		if( ZAdaptorLoginMessage::get(src, len, &msg) ) {
			mServer->clientLogin(this, &msg);
			return ZAdaptorLoginMessage::Length;
		}
	} else if ( ZAdaptorMarketDataSubMessage::Type == type && len >= ZAdaptorMarketDataSubMessage::Length) {
		ZAdaptorMarketDataSubMessage msg;
		if( ZAdaptorMarketDataSubMessage::get(src, len, &msg) ) {
			mServer->reqMarketData(this, &msg);
			return ZAdaptorMarketDataSubMessage::Length;
		}
	}

	return -1;
}

void AdaptorSocket::OnReceive(int nErrorCode) {
	int n = Receive(mBuffer+mBufLen, mBufSize - mBufLen);

	mBufLen += n;
	// process buffer
	mProcBuffer();

	CSocket::OnReceive(nErrorCode);
}

void AdaptorSocket::OnClose(int nErrorCode) {
	mServer->clientClosed(this);
	CSocket::OnClose(nErrorCode);
}